package com.yequan.hbb.customview;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.RectF;
import android.graphics.Shader;
import android.util.AttributeSet;
import android.view.View;
import android.widget.ImageView;

/**
 * Created by Administrator on 2016/10/14.
 */

public class ConerImageView extends ImageView {

    private Paint paint;
    private Bitmap bitmap;
    private BitmapShader bitmapShader;
    private RectF rectF;
    private Matrix matrix;
    private boolean isCircle;

    public ConerImageView(Context context) {
        this(context,null);
    }


    public ConerImageView(Context context, AttributeSet attrs) {
        this(context, attrs,0);
    }


    public ConerImageView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        paint = new Paint();
        paint.setAntiAlias(true);
        matrix = new Matrix();

    }

    public void setCircle(boolean circle) {
        isCircle = circle;
        postInvalidate();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        if (rectF!=null) {
            if (isCircle){
                canvas.drawRoundRect(rectF, getWidth()/2, getHeight()/2, paint);
            }else
            canvas.drawRoundRect(rectF, 20, 20, paint);
        }
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }

    public void setBitmap(Bitmap bitmap) {
        this.bitmap = bitmap;
        bitmapShader=new BitmapShader(bitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
        //float scale=0;

       // scale= Math.max(getHeight() * 1.0f / bitmap.getHeight(), getWidth() * 1.0f / bitmap.getWidth());

        float scaleX=0,scaleY=0;
        scaleY=getHeight() * 1.0f / bitmap.getHeight();
        scaleX=getWidth() * 1.0f / bitmap.getWidth();
        matrix.setScale(scaleX,scaleY);

        bitmapShader.setLocalMatrix(matrix);
        paint.setShader(bitmapShader);
        rectF=new RectF(0,0,getWidth(),getHeight());
        invalidate();
    }
}
